package university;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet(description = "Login Authentication servlet", urlPatterns = { "/LoginAuth" })
public class LoginAuth extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write(
				"E: Access denied. use Post method to call the servlet.");
		response.getWriter().close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Context ctx = null;
		DataSource ds = null;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			ctx = new InitialContext();
		} catch (NamingException e) {
			System.out.println("context:" + e.toString());
		}

		try {
			ds = (DataSource) ctx.lookup("jdbc/mydata");
		} catch (NamingException e) {
			System.out.println("datasource:" + e.toString());
		}
		try {
			con = ds.getConnection();
		} catch (SQLException e) {
			System.out.println("connection" + e.toString());
		}
		try {
			stmt = con
					.prepareStatement("select password from UniLoginDB where login=?");
			stmt.setString(1, request.getParameter("login"));
		} catch (SQLException e) {
			System.out.println("prepared stmt:" + e.toString());
		}
		try {
			rs = stmt.executeQuery();
		} catch (SQLException e) {
			System.out.println("exec Q:" + e.toString());
		}
		try {
			rs.next();
			if (rs.getString(1).equals(request.getParameter("paswd"))) {
				response.getWriter().write("Login success, loading.....");
				// forward();
			} else {
				response.getWriter().write(
						"Acces Denied: invalid Login/Password.");
			}
		} catch (SQLException e) {
			System.out.println("ResultSet:" + e.toString());
		}
		// try {
		// rs.close();
		// stmt.close();
		// con.close();
		// } catch (SQLException e) {
		// System.out.println("Close resource:" + e.toString());
		// }
		response.getWriter().close();
	}
}

/*
 * datebase information: (PostgreSQL syntax)
 * 
 * drop table uniloginDB;
 * 
 * Create Table UniLoginDB( login varchar(20) Primary key, password varchar(20)
 * not null );
 * 
 * insert into UniLoginDB values ('karthik','hello'); insert into UniLoginDB
 * values ('root','toor'); insert into UniLoginDB values ('user','welcome');
 */